﻿using UnityEngine;
using System.Collections;
using System;

/// <summary>
/// 玩家，处理移动方法
/// </summary>
public class Player : MonoBehaviour {

    public GameObject tankMeshRender;
    public MeshRenderer[] meshs;
    public Transform firePoint;
    public PlayerUI playerUI;
    
    float moveSpeed = 10f;
    float rotSpeed = 5;

    public UserData userData;
    CharacterController controller;
    GameObject bulletPrefab;

    void Start()
    {
        controller = this.GetComponent<CharacterController>();
        bulletPrefab = Resources.Load<GameObject>("Bullet");
    }

    public void SetUserData(UserData user)
    {
        userData = user;

        foreach (var item in meshs)
        {
            item.material.color = user.color;
        }
        playerUI.SetName(user.username);
        SetHp(user.hp);
    }

    //同步人物的位置
    public void Reset(Vector3 position,Vector3 rotation)
    {
        transform.position = position;
        transform.eulerAngles = rotation;
    }


    Vector2 lastDirect = Vector2.zero;

    //让物体移动
    public void Move(Vector2 direct)
    {
        lastDirect = direct;
    }


    Vector3 move = Vector3.zero;
    Vector3 rota = Vector3.zero;
    private void FixedUpdate()
    {
        if(lastDirect != Vector2.zero)
        {
            //人物的位移
            move.Set(0,0, lastDirect.y);
            move = transform.TransformDirection(move);
            controller.SimpleMove(move * moveSpeed);

            //人物的旋转
            rota.Set(0, lastDirect.x, 0);
            transform.Rotate(rota * rotSpeed);
        }
    }

    //调用子节点下的ui
    public void SetArrowLegth(float force)
    {
        playerUI.SetArrow(force);
    }

    //坦克发射子弹的方法
    public void Fire(float force,bool islocal=false)
    {
        GameObject go = Instantiate(bulletPrefab);
        go.transform.position = firePoint.position;
        go.transform.rotation = firePoint.rotation;

        //给物体施加脉冲力
        Bullet bullet = go.GetComponent<Bullet>();
        bullet.username = this.userData.username;
        bullet.isLocalBullet = islocal;

        go.GetComponent<Rigidbody>().AddForce(transform.forward * force, ForceMode.Impulse);
    }

    public void SetHp(int hp)
    {
        userData.hp = hp;
        float percent = (float)userData.hp / 10;
        playerUI.SetHp(percent);
    }

    public void OnDead()
    {
        GameObject prefab = Resources.Load<GameObject>("BustedTank");
        GameObject go = Instantiate(prefab);
        go.transform.position = transform.position;
        go.transform.rotation = transform.rotation;
        go.GetComponent<MeshRenderer>().material.color = userData.color;

        this.Move(Vector2.zero);
        tankMeshRender.SetActive(false);

        this.GetComponent<CharacterController>().enabled = false;
        //如果是主角，删除Local控制器
        var controller = this.GetComponent<LocalController>();
        if (controller)
        {
            Destroy(controller);
        }
    }
}


